﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;

namespace ReconUI
{
    public partial class RoleMenuMapping : System.Web.UI.Page
    {
        DBFactory db;
        public List<int> checkedValues;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (((UserVO)Session["CurrentUserVO"]) == null)
            {
                Response.Redirect("ReconSignIn.aspx");
            }
            if (!IsPostBack)
            {
                btnSubmit.Visible = false;
                loadRoles();
            }
        }

        //protected void btnGo_Click(object sender, EventArgs e)
        //{
        //    //////// Get the list of all menus and bind to grid
        //    //////loadMenus(grvMenu);
        //    //////// Get the list of menus which are assined to the selected role
        //    //////getRoleMenus();
        //}

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                insertRoleMenuMapping();
            }
            catch (Exception ex)
            {
                
            }
        }


        private void loadRoles()
        {
            db = new DBFactory();
            DataTable dtRole = null; 
            try
            {
                dtRole = db.GetAllRoles();

                if (dtRole != null && dtRole.Rows.Count > 0)
                {
                    ddlRole.Items.Insert(0, "Select Role");
                    ddlRole.Items[0].Value = "0";

                    for (int i = 0; i < dtRole.Rows.Count; i++)
                    {
                        ddlRole.Items.Add(dtRole.Rows[i].ItemArray[2].ToString().Trim());
                        ddlRole.Items[i + 1].Value = (dtRole.Rows[i].ItemArray[0].ToString().Trim());
                    }
                }

                //if (ddlRole.GetType().Name == "DropDownList")
                //{
                    //ddlRole.Items.Insert(0, "Select Role");
                    //ddlRole.Items[0].Value = "0";
                //}
            }
            catch (Exception ex)
            {
                
            }
            finally
            {
                if (dtRole != null)
                {
                    dtRole.Dispose();
                }
                dtRole = null;
                db = null;                
            }

        }

        public void loadMenus(GridView control)
        {
            db = new DBFactory();
            DataTable dtMenu = null;
            try
            {
                dtMenu = db.GetAllMenus();

                if (dtMenu != null && dtMenu.Rows.Count > 0)
                {
                    control.DataSource = dtMenu;
                    control.DataBind();
                }
            }
            catch (Exception ex)
            {
                
            }
            finally
            {
                if (dtMenu != null)
                {
                    dtMenu.Dispose();
                }
                dtMenu = null;
                db = null;               
            }
        }

        public void getRoleMenus()
        {
            db = new DBFactory();
            DataTable dtRoleMenus = null;
            try
            {
                dtRoleMenus = db.GetMenuForRole(ddlRole.SelectedValue.ToString().Trim());
                //Now mark checkbox as 'selected' if any menus are assigned to the selected role.
                {
                    if (dtRoleMenus.Rows.Count > 0)
                    {
                        checkedValues = new List<int>();
                        //Get the menu id(s) which are assined to role , into list.
                        for (int _intCounter = 0; _intCounter <= dtRoleMenus.Rows.Count - 1; _intCounter++)
                        {
                            int menuID = Convert.ToInt32(dtRoleMenus.Rows[_intCounter]["Menu_Id"]);
                            checkedValues.Add(menuID);
                        }
                        Session["ExistingMenu"] = checkedValues.ToList<int>();
                        //Comapare menus from list with the grid items and then mark checkbox as selected if matching
                        foreach (GridViewRow row in grvMenu.Rows)
                        {
                            HtmlInputCheckBox chk = (HtmlInputCheckBox)row.Cells[0].FindControl("chkIndividual");
                            int menuID = Convert.ToInt32(grvMenu.DataKeys[row.RowIndex].Value);
                            if ((checkedValues.Contains(menuID)))
                            {
                                chk.Checked = true;
                            }
                        }
                        //If All menus are selected then mark 'SelectAll' checkbox
                        if (checkedValues.Count == grvMenu.Rows.Count)
                        {
                            //CType(grvMenu.HeaderRow.FindControl("chkSelectAll"), HtmlInputCheckBox).Checked = True
                        }
                    }
                    btnSubmit.Visible = true;
                }
            }
            catch (Exception ex)
            {
                btnSubmit.Visible = false;
            }
            finally
            {
                if (dtRoleMenus != null)
                {
                    dtRoleMenus.Dispose();
                }
                dtRoleMenus = null;
                db = null;
            }
        }

        public void insertRoleMenuMapping()
        {
            db = new DBFactory();
            //function used to insert map_rolemenu to the database
            DataSet _ObjDataSet = new DataSet();
            string _strMenuIDS = "";
            Int32 _intCounter = 0;
            int retval = 0;
            foreach (GridViewRow row in grvMenu.Rows)
            {
                HtmlInputCheckBox chk = (HtmlInputCheckBox)row.Cells[0].FindControl("chkIndividual");
                int menuID = Convert.ToInt32(grvMenu.DataKeys[row.RowIndex].Value);
                //grvMenu.DataKeys(row.RowIndex)("Menu_Id")
                if (chk.Checked)
                {
                    _intCounter = _intCounter + 1;
                    _strMenuIDS = _strMenuIDS + "," + menuID;
                }
            }
            if (_intCounter > 0)
            {
                _strMenuIDS = _strMenuIDS.Substring(1);
            }

            try
            {
                //Comapare menus from list with the grid items and then mark checkbox as selected if matching
                if (Session["ExistingMenu"] != null)
                {
                    checkedValues = (List<int>)Session["ExistingMenu"];
                }
                foreach (GridViewRow row in grvMenu.Rows)
                {
                    HtmlInputCheckBox chk = (HtmlInputCheckBox)row.Cells[0].FindControl("chkIndividual");
                    int menuID = Convert.ToInt32(grvMenu.DataKeys[row.RowIndex].Value);
                    if ((checkedValues.Contains(menuID)))
                    {
                        //select count(1) from reconengine.mast_role_menu_maint where role_id = 'Customer' and menu_id = '15';
                        retval = db.removeRoleMenuMapping(ddlRole.SelectedValue.ToString().Trim(), Convert.ToString(menuID));
                        checkedValues.Remove(menuID);
                        //chk.Checked = true;
                    }
                    if (chk.Checked)
                    {
                       
                            //if ((checkedValues.Contains(menuID)))
                            //{
                            //    checkedValues.Remove(menuID);
                            //    //chk.Checked = true;
                            //}
                            //else
                            //{
                                retval = db.addRoleMenuMapping(ddlRole.SelectedValue.ToString().Trim(), Convert.ToString(menuID), 1, ((UserVO)Session["CurrentUserVO"]).userId);
                                _intCounter = _intCounter + 1;
                            //}
                    }
                   
                    
                   
                }               
                if (retval == 1)
                {
                    //ClientScript.RegisterClientScriptBlock(this.GetType(), "ErrorStatus", "<script> alert('Role-Menu mapping done Successfully!');</script>");
                    lblMessage.Text = "Role-Menu mapping done Successfully!";
                    btnClickPopup.Show();
                    ClearFields();
                    btnSubmit.Visible = false;
                }
                else if (retval == 2)
                {
                    //ClientScript.RegisterClientScriptBlock(this.GetType(), "ErrorStatus", "<script> alert('Can not delete Role-Menu mapping for the selected Role!');</script>");
                    lblMessage.Text = "Can not delete Role-Menu mapping for the selected Role!";
                    btnClickPopup.Show();
                    ClearFields();
                    btnSubmit.Visible = false;
                }
                else
                {
                    //ClientScript.RegisterClientScriptBlock(this.GetType(), "ErrorStatus", "<script> alert('Error while mapping Role-Menu.');</script>");
                    lblMessage.Text = "Error while mapping Role-Menu.";
                    btnClickPopup.Show();
                }
            }
            catch (Exception ex)
            {
                //ClientScript.RegisterClientScriptBlock(this.GetType(), "ErrorStatus", "<script> alert('Error while mapping role-menu');</script>");
                lblMessage.Text = "Error while mapping role-menu";
                btnClickPopup.Show();
            }
            finally
            {
                if (_ObjDataSet != null)
                {
                    _ObjDataSet.Dispose();
                }
                _ObjDataSet = null;
                _strMenuIDS = null;
                db = null;
                Session["ExistingMenu"] = null;
               
            }

        }

        private void ClearFields()
        {
            ddlRole.ClearSelection();
            ddlRole.SelectedValue = "0";
            grvMenu.DataSource = null;
            grvMenu.DataBind();
            Session["ExistingMenu"] = null;
            
        }

        protected void ddlRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get the list of all menus and bind to grid
            loadMenus(grvMenu);
            // Get the list of menus which are assined to the selected role
            getRoleMenus();
        }

        protected void btnok_Click(object sender, EventArgs e)
        {
            btnClickPopup.Hide();
        }
    }
}